package org.dromara.system.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.XcxLoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.FXcxUserBo;
import org.dromara.system.domain.vo.FXcxUserVo;
import org.dromara.system.domain.FXcxUser;
import org.dromara.system.mapper.FXcxUserMapper;
import org.dromara.system.service.IFXcxUserService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 小程序用户Service业务层处理
 *
 * @author Zhangshuming
 * @date 2024-03-27
 */
@RequiredArgsConstructor
@Service
public class FXcxUserServiceImpl implements IFXcxUserService {

    private final FXcxUserMapper baseMapper;

    private final WxMaService wxMaService;

    /**
     * 查询小程序用户
     */
    @Override
    public FXcxUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询小程序用户列表
     */
    @Override
    public TableDataInfo<FXcxUserVo> queryPageList(FXcxUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FXcxUser> lqw = buildQueryWrapper(bo);
        Page<FXcxUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询小程序用户列表
     */
    @Override
    public List<FXcxUserVo> queryList(FXcxUserBo bo) {
        LambdaQueryWrapper<FXcxUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FXcxUser> buildQueryWrapper(FXcxUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FXcxUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOpenid()), FXcxUser::getOpenid, bo.getOpenid());
        lqw.like(StringUtils.isNotBlank(bo.getNickename()), FXcxUser::getNickename, bo.getNickename());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), FXcxUser::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getIsVip()), FXcxUser::getIsVip, bo.getIsVip());
        lqw.eq(bo.getMoney() != null, FXcxUser::getMoney, bo.getMoney());
        lqw.eq(bo.getCreateTime() != null, FXcxUser::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getPhone() != null, FXcxUser::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlg()), FXcxUser::getDelFlg, bo.getDelFlg());
        return lqw;
    }

    /**
     * 新增小程序用户
     */
    @Override
    public Boolean insertByBo(FXcxUserBo bo) {
        FXcxUser add = MapstructUtils.convert(bo, FXcxUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改小程序用户
     */
    @Override
    public Boolean updateByBo(FXcxUserBo bo) {
        FXcxUser update = MapstructUtils.convert(bo, FXcxUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FXcxUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除小程序用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public FXcxUserVo selectUserByOpenid(String openid) {
        LambdaQueryWrapper<FXcxUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FXcxUser::getOpenid, openid);
        return baseMapper.selectVoOne(wrapper);
    }

    @Override
    public FXcxUserVo newXcxUser(String openid) {
        FXcxUserBo fXcxUserBo = new FXcxUserBo();
        fXcxUserBo.setOpenid(openid);
        int insert = baseMapper.insert(BeanUtil.toBean(fXcxUserBo, FXcxUser.class));

        //Boolean aBoolean = insertByBo(fXcxUserBo);

        if (insert <= 0){
            throw new  ServiceException("新增小程序用户失败");
        }
        return BeanUtil.toBean(fXcxUserBo, FXcxUserVo.class);
    }

    @Override
    public R<Boolean> updateUser(String nikename, String avatar, String phoneEncryptedData, String phoneIv, String xcxCode, String province, String city) {
        XcxLoginUser loginUser = (XcxLoginUser) LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser)){
            return R.fail("用户未登录");
        }
        Long userId = loginUser.getUserId();
        FXcxUser fXcxUser = baseMapper.selectById(userId);
        WxMaPhoneNumberInfo phoneNoInfo = new WxMaPhoneNumberInfo();
        if(ObjectUtil.isNull(fXcxUser)){
            throw  new ServiceException("用户不存在");
        }
        fXcxUser.setProvince(province);
        fXcxUser.setCity(city);
        fXcxUser.setNickename(nikename);
        fXcxUser.setAvatar(avatar);
        if (StringUtils.isNotBlank(phoneEncryptedData)){
            String sessionKey1 = loginUser.getSessionKey();
            phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey1,phoneEncryptedData,phoneIv);
            fXcxUser.setPhone(phoneNoInfo.getPhoneNumber());
        }
        return R.ok(baseMapper.updateById(fXcxUser)> 0);
    }
}
